# -*- coding: utf-8 -*-
from functools import partial

from sqlalchemy.exc import IntegrityError

from common.lottery.cyclical.abstract import activity as base
from common.lottery.cyclical.js_ks.db.activity import calc_miss
from common.utils.decorator import sql_wrapper
from common.lottery import LOTTERY_TYPE


fullfill_result = sql_wrapper(
    partial(base.fullfill_result, LOTTERY_TYPE.GX_KS))


get_latest_term = sql_wrapper(
    partial(base.get_latest_term, LOTTERY_TYPE.GX_KS))


get_activity_by_term = sql_wrapper(
    partial(base.get_activity_by_term, LOTTERY_TYPE.GX_KS))


stop_term = sql_wrapper(
    partial(base.stop_term, LOTTERY_TYPE.GX_KS))


create_new_term = sql_wrapper(
    partial(base.create_new_term, LOTTERY_TYPE.GX_KS))


get_stats_by_term = sql_wrapper(
    partial(base.get_stats_by_term, LOTTERY_TYPE.GX_KS))

get_activity_stats = sql_wrapper(
    partial(base.get_activity_stats, LOTTERY_TYPE.GX_KS))


@sql_wrapper
def insert_stats(term, number, last_stats):
    trend, save = base.generate_trend(
        LOTTERY_TYPE.GX_KS, term, number, last_stats)

    trend, save = calc_miss(last_stats, number, save, trend)
    if save:
        try:
            trend.save()
        except IntegrityError:
            pass

    return trend
